#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>

typedef struct NodeInfo{
    char name[20];
    int size;
    char creata_date;
    struct NodeInfo *next;
} Node;

Node *createHead(void); //创建链表头指针

int main()
{
    Node *head = createHead(); //创建链表头指针
    addCfiles(".", head); //传入当前目录地址和链表头指针，将所有.c文件信息添加到链表中
    Node *p = head->next;
    while(p!= NULL){
        printf("%s\t%d\n", p->name, p->size);
        p = p->next;
    }
    return 0;
}


/*
    函数功能：创建链表头指针及头结点
    参数列表：无
    返回值：头指针
*/
Node *createHead(void){
    Node *head = (Node*)malloc(sizeof(Node));   //创建头结点
    if(head == NULL){
        printf("malloc error!\n");
        exit(1);
    }
    head->next = NULL;
    return head;
}

/*
    函数功能：传入目录地址和链表头指针，将所有.c文件信息添加到链表中，如果为目录，则递归调用函数
    参数列表：目录地址，链表头指针
    返回值：无
*/
void addCfiles(char *dir, Node *head){
    DIR *dp;
    struct dirent *dirp;
    if((dp = opendir(dir)) == NULL){
        printf("opendir error!\n");
        exit(1);
    }
    while((dirp = readdir(dp)) != NULL){
        if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0){
            continue;
        }
        if(dirp->d_type == DT_DIR){
            char path[100];
            strcpy(path, dir);
            strcat(path, "/");
            strcat(path, dirp->d_name);
            addCfiles(path, head);
        }else if(strcmp(dirp->d_name + strlen(dirp->d_name) - 2, ".c") == 0){
            Node *p = (Node*)malloc(sizeof(Node));
            if(p == NULL){
                printf("malloc error!\n");
                exit(1);
            }
            strcpy(p->name, dirp->d_name);
            p->size = dirp->d_reclen;
            p->next = head->next;
            head->next = p;
        }
    }
    closedir(dp);
}